package com.mantru.iotpot.setting;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadTask {
    private final String mFileUrl;
    private final DownloadListener mDownloadListener;
    private final File mDownloadFile;
    private DownloadThread mDownloadThread;
    private boolean mIsCancelled;

    public DownloadTask(String fileUrl, File downloadFile, DownloadListener downloadListener) {
        mFileUrl = fileUrl;
        mDownloadFile = downloadFile;
        mDownloadListener = downloadListener;
    }

    public void start() {
        mIsCancelled = false;
        mDownloadThread = new DownloadThread();
        mDownloadThread.start();
    }

    public void cancel() {
        if (mDownloadThread != null && mDownloadThread.isAlive()) {
            mIsCancelled = true;
            mDownloadThread.interrupt();
            Log.d("DownloadTask", "下载任务已取消");
        }
    }

    private class DownloadThread extends Thread {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(mFileUrl)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    long contentLength = response.body().contentLength();
                    if (contentLength == 0) {
                        Log.e("DownloadTask", "文件大小为 0，无法进行下载");
                        if (mDownloadListener != null) {
                            mDownloadListener.onDownloadFailed("文件大小为 0，无法进行下载");
                        }
                        return;
                    }
                    InputStream inputStream = null;
                    FileOutputStream fileOutputStream = null;
                    try {
                        byte[] buffer = new byte[8192]; // 每次读取 8KB
                        long totalBytesRead = 0; // 已下载的总字节数
                        inputStream = response.body().byteStream();
                        fileOutputStream = new FileOutputStream(mDownloadFile);
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            if (mIsCancelled) {
                                break;
                            }
                            fileOutputStream.write(buffer, 0, bytesRead);
                            totalBytesRead += bytesRead;
                            // 计算进度百分比
                            final int progress = (int) ((totalBytesRead * 100) / contentLength);
                            // 更新 UI
                            if (mDownloadListener != null) {
                                mDownloadListener.onProgressUpdate(progress);
                            }
                        }
                        // 下载完成后的操作
                        if (!mIsCancelled) {
                            if (mDownloadListener != null) {
                                mDownloadListener.onDownloadComplete();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("DownloadTask", "文件下载失败: " + e.getMessage());
                        if (mDownloadListener != null) {
                            mDownloadListener.onDownloadFailed("文件下载失败: " + e.getMessage());
                        }
                    } finally {
                        // 关闭资源
                        if (inputStream != null) {
                            try {
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    Log.e("DownloadTask", "文件下载失败，HTTP 错误码: " + response.code());
                    if (mDownloadListener != null) {
                        mDownloadListener.onDownloadFailed("文件下载失败，HTTP 错误码: " + response.code());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("DownloadTask", "文件下载请求失败: " + e.getMessage());
                if (mDownloadListener != null) {
                    mDownloadListener.onDownloadFailed("文件下载请求失败: " + e.getMessage());
                }
            }
        }
    }

    public interface DownloadListener {
        void onProgressUpdate(int progress);
        void onDownloadComplete();
        void onDownloadFailed(String message);
    }
}
